package com.atguigu.gulimall.order.listener;

import com.atguigu.common.contrsant.OrderConstant;
import com.atguigu.common.dto.mq.SeckillSkuDTO;
import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.service.OrderService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @author meiyn
 * @date 2021/7/24 10:52
 */
@RabbitListener(queues = OrderConstant.ORDER_RELEASE_ORDER_QUEUE)
@Service
public class OrderCloseListener {
    @Resource
    private OrderService orderService;

//    @Resource
//    private AlipayTemplate alipayTemplate;

    @RabbitHandler
    public void handleOrderClose(OrderEntity order, Message message, Channel channel) throws IOException {
        System.out.println("收到过期订单的消息，准备关闭订单 order->"+order);

        try {

            orderService.closeOrder(order);
            // TODO 避免因为网络问题、或者用户正在支付中导致的订单与时间冲突问题，手动调用支付宝收单（关闭订单）
            // 可能因为内网穿透的问题，提示订单不存在，关单失败，先保留
//            String result = alipayTemplate.closePay(order.getOrderSn());

            //手动回复RabbitMQ，订单已经关闭成功，broker将移除此消息
            //multiple: 不用批量模式
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            e.printStackTrace();
            //订单关闭异常，消息拒绝，重新放入消息队列，让别人继续解锁消费
            //requeue：拒绝消息
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }

    @RabbitHandler
    public void handleSeckillOrderClose(SeckillSkuDTO seckillSkuDTO, Message message, Channel channel) throws IOException {
        System.out.println("收到过期秒杀订单的消息");

        try {

            orderService.closeSeckillOrder(seckillSkuDTO);
            // TODO 避免因为网络问题、或者用户正在支付中导致的订单与时间冲突问题，手动调用支付宝收单
            // 可能因为内网穿透的问题，提示订单不存在，关单失败，先保留
//            String result = alipayTemplate.closePay(order.getOrderSn());
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            e.printStackTrace();
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }
}
